<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <template v-slot:after>
          <el-button size="small" type="primary" @click="handleAddPermission({id: '0', type: 1})">添加权限</el-button>
        </template>
      </page-tools>

      <!-- 权限列表 -->
      <el-card>
        <el-table border :data="list" row-key="id">
          <el-table-column label="菜单名称" align="left" prop="name" />
          <el-table-column label="权限标识" align="center" prop="code" />
          <el-table-column label="描述" align="center" prop="description" />
          <el-table-column label="操作" align="center">
            <template v-slot="{row}">
              <!-- 添加按钮只在 访问权的层级显示 type==1 时才显示添加按钮-->
              <el-button v-if="row.type==1" type="text" @click="handleAddPermission({id: row.id, type: 2})">添加</el-button>
              <el-button type="text" @click="handleEditPermission(row.id)">编辑</el-button>
              <el-button type="text" @click="delPermission(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <add-permission
      ref="addPermissionRef"
      :show-permit-dialog.sync="showPermitDialog"
      :node="node"
      @addPermission="getPermissionList"
    />
  </div>
</template>

<script>
import { getPermissionList, delPermission } from '@/api/permission'
import { tranListToTreeData } from '@/utils/index'
import AddPermission from './components/add-permission.vue'
export default {
  components: { AddPermission },
  data() {
    return {
      list: [],
      showPermitDialog: false, // 显示添加或者编辑弹框
      rows: { // 添加才需要
        id: 0,
        type: 1
      } // 当前行需要的数据   访问一级页面  pid: "0"   二级等于上一级的id   一级添加 type=1  二级添加type=2
    }
  },
  mounted() {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      this.list = tranListToTreeData(await getPermissionList(), '0') // 转化为树形结构
    },
    handleAddPermission(node) { // { id: "0", type: 1/2}   => id:为"0"是添加一级访问页面等于二级页面的pid, 二级的id则等于三级的pid,   type为1,表示为访问页, 能新增按钮权限, 为2表示正处于按钮权限位置, 不能新增下一级
      this.node = node
      this.showPermitDialog = true
    },
    // 点击删除权限
    delPermission(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delPermission(id)
      }).then(() => {
        this.getPermissionList()
        this.$message.success('删除成功')
      }).catch(() => {})
    },
    // 点击编辑权限
    async handleEditPermission(id) {
      await this.$refs.addPermissionRef.getPermissionDetail(id)
      this.showPermitDialog = true
    }
  }
}
</script>

<style>

</style>
